//
//  LWHomeViewController.m
//  1.28  weibo
//
//  Created by mac on 15/1/30.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "LWHomeViewController.h"
#import "LWScanController.h"
#import "LWTitleBtn.h"
#import "LWTextTableViewController.h"
#import "AFNetworking.h"
#import "LWAccount.h"
#import "UIImageView+WebCache.h"
#import "LWPhotos.h"
#import "LWUser.h"
#import "LWstatuses.h"
#import "LWTableFootView.h"
#import "MJRefresh.h"
#import "LWTableViewCell.h"
#import "LWNetWorkTools.h"
#import "LWStatuseRequset.h"
#import "LWStatuseResult.h"
@interface LWHomeViewController ()
/**
 *  微博数组(里面存储的是所有微博的字典)
 */
@property (nonatomic, strong) NSMutableArray *statuses;


@end

@implementation LWHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  //1.创建导航按钮
    [self setupNav];
    //2.初始化默认界面
    
    if (self.defaultView != nil) {
        
        self.defaultView.icon = @"visitordiscover_feed_image_house";
        self.defaultView.content = @"当你关注一些人以后，他们发布的最新消息会显示在这里";
    }else{
        //1.获取用户的信息
        [self setupUserInfo];
//        //2.获取微博信息
//        [self loadNewStatuse:nil];
        //3.刷新数据
        [self setupRefreshControl];
    }

}
#pragma mark - 获取用户本人的信息
- (void)setupUserInfo{
  
    LWNetWorkTools *tools = [LWNetWorkTools shareNetWorkTools];
    [tools loadUserInfo:^(LWUser *user) {
        
        LWAccount *account = [LWAccount accountFromSandBox];
        NSString *iconUrlString = user.profile_image_url;
        if ([account.profile_image_url isEqualToString:iconUrlString]) {
            return ;
        }
        account.profile_image_url = iconUrlString;
        [account save];
        
    } failure:^(NSError *error) {
        LWLog(@"error%@",error);
    }];
    
}
#pragma mark - 刷新Refresh
- (void)setupRefreshControl{

    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatuse:)];
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreStatuses)];
    [self.tableView headerBeginRefreshing];
}
#pragma mark - 上啦刷新的实现

- (void)loadMoreStatuses{

    LWStatuseRequset *parameters = [[LWStatuseRequset alloc] init];
    parameters.access_token = [LWAccount accountFromSandBox].access_token;
    NSString *max_id = [[self.statuses lastObject] idstr];
    if (self.statuses != nil) {
        parameters.max_id = @([max_id longLongValue] - 1);
    }
    [[LWNetWorkTools shareNetWorkTools] loadHomeStatusesWithParameters:parameters success:^(LWStatuseResult *result) {
        
        [self.statuses addObjectsFromArray:result.statuses];
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
        
    } failure:^(NSError *error) {
        
        [self.tableView footerEndRefreshing];

    }];
    
}
- (void)loadNewStatuse:(UIRefreshControl *)refresh{

    //0. 清空badgeValue
    self.tabBarItem.badgeValue = @"";
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    //2.封装参数
    LWAccount *account = [LWAccount accountFromSandBox];
    LWStatuseRequset *parameters = [[LWStatuseRequset alloc] init];
    parameters.access_token = account.access_token;
    //取出数组中的第一个参数
    NSString *firstIdre = [[self.statuses firstObject] idstr];
    if (firstIdre != nil) {
        parameters.since_id = @([firstIdre longLongValue]);
    }
   
    //3.发送请求
    [[LWNetWorkTools shareNetWorkTools] loadHomeStatusesWithParameters:parameters success:^(LWStatuseResult *result) {
        
                //将字典添加到数组中
        NSRange range = NSMakeRange(0, result.statuses.count);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:result.statuses atIndexes:indexSet];
        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        //刷新提醒
        [self showNewStatusWithCount:result.statuses.count];
        
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
    }];
}
#pragma mark - 下拉刷仙提醒
- (void)showNewStatusWithCount:(NSInteger)count{
    //1.创建lable
    UILabel *infoLable = [[UILabel alloc] init];
    infoLable.backgroundColor = [UIColor blueColor];
    infoLable.textAlignment = NSTextAlignmentCenter;
    CGFloat infoLableW = self.view.width;
    CGFloat infoLableH = 44;
    CGFloat infoLableX = 0 ;
    CGFloat infoLableY = 64 - infoLableH;
    infoLable.frame = CGRectMake(infoLableX, infoLableY, infoLableW, infoLableH);
    //2.设置lable的显示内容
    if (count > 0) {
        infoLable.text = [NSString stringWithFormat:@"刷新到%tu条数据",count];
    }else{
    infoLable.text = @"没有刷新到数据";
    }
    //3.将lable添加到视图上
    UINavigationBar *navBar = self.navigationController.navigationBar;
    [self.navigationController.view insertSubview:infoLable belowSubview:navBar];
    //4.执行动画
    [UIView animateWithDuration:1.0 animations:^{
        infoLable.transform = CGAffineTransformMakeTranslation(0, infoLableH);
    } completion:^(BOOL finished) {
        [UIView animateKeyframesWithDuration:1.0 delay:1.5 options:0 animations:^{
            infoLable.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [infoLable removeFromSuperview];
        }];
    }];
}

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.statuses.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    LWTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"coustomCell" forIndexPath:indexPath];
    cell.status = self.statuses[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    LWTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"coustomCell"];
    return [cell cellHeightWithStatus:self.statuses[indexPath.row]];
}

- (void)setupNav{
    //导航栏左右两个按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itmeWith:@"navigationbar_friendsearch" highlightedImage:@"navigationbar_friendsearch_highlighted" target:self action:@selector(leftClick)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itmeWith:@"navigationbar_pop" highlightedImage:@"navigationbar_pop_highlighted" target:self action:@selector(rightClick)];
    
    //创建标题按钮
    LWTitleBtn *titleBtn = [[LWTitleBtn alloc] init];
    [titleBtn setTitle:@"首页" forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    [titleBtn sizeToFit];
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView = titleBtn;

}

#pragma mark - 监听按钮的点击

- (void)titleBtnClick:(LWTitleBtn *)titleBtn{
    
    titleBtn.selected = !titleBtn.selected;
    
    //创建菜单容器视图
    LWTextTableViewController *text = [[LWTextTableViewController alloc] init];
    text.view.size = CGSizeMake(150, 200);
    
    [LWPopMenueView popFrom:titleBtn cntentVc:text dismissBlock:^{
        titleBtn.selected = !titleBtn.selected;
    }];
}
#pragma mark - 监听按钮的点击

- (void)leftClick{
    
}
- (void)rightClick{
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"LWScanController" bundle:nil];
    LWScanController *scan = [sb instantiateInitialViewController];
    [self presentViewController:scan animated:YES completion:nil];
}

#pragma mark - 开始旋转

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    [self.defaultView startRotate];
}

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    [self.defaultView stopRotate];
}

- (NSMutableArray *)statuses{

    if (_statuses == nil) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}

@end
